#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>

#include "../Comm/Util.hpp"
#include "../Comm/Log.hpp"

namespace ns_run
{
    using namespace ns_util;
    using namespace ns_log;
    class Run
    {
    public:
        Run(){}
        ~Run(){}
        static void SerLimit(int _cpu_limit, int _mem_limit)
        {
            struct rlimit r_cpu;
            // cpu
            r_cpu.rlim_cur = _cpu_limit;
            r_cpu.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &r_cpu);

            // 内存
            struct rlimit r_mem;
            r_mem.rlim_cur = _mem_limit * 1024;
            r_mem.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_AS, &r_mem);
        }
        static int Runner(const std::string& file_name, int _cpu_limit, int _mem_limit)
        {
            umask(0);
            std::string _execute = PathUtil::Exe(file_name);
            std::string _stdin = PathUtil::Stdin(file_name);
            std::string _stdout = PathUtil::Stdout(file_name);
            std::string _stderr = PathUtil::Stderr(file_name);

            int stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);
            if(stdin_fd < 0 || stdout_fd < 0 || stderr_fd < 0)
            {
                LOG(ERROR) << "打开文件失败" << "\n";
                return -1;
            }

            pid_t pid = fork();
            if(pid < 0)
            {
                close(stdin_fd);
                close(stdout_fd);
                close(stderr_fd);
                LOG(ERROR) << "创建子进程失败" << "\n";
                return -2;
            }
            else if(pid == 0)
            {
                dup2(stdin_fd, 0);
                dup2(stdout_fd, 1);
                dup2(stderr_fd, 2);

                // cpu与内存限制
                SerLimit(_cpu_limit, _mem_limit);

                // 子进程完成运行任务
                execl(_execute.c_str(), _execute.c_str(), nullptr);
                exit(1);
            }
            else 
            {
                close(stdin_fd);
                close(stdout_fd);
                close(stderr_fd);
                int status = 0;
                waitpid(pid, &status, 0);
                LOG(INFO) << "运行完毕, info: " << (status & 0x7F) << "\n";
                return status & 0x7F;
            }
        }
    };
}